#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-12-18 11:49:51
# @Author  : PiaoYun (piaoyunsoft@163.com)
# @Link    : http://www.dllhook.com
# @Version : $Id$

from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet import reactor, task
from twisted.internet.protocol import ClientCreator
from twisted.internet.protocol import ClientFactory

from sys import stdout

class WeChatClient(Protocol):
    def connectionMade(self):
        # 连接上服务器后，打印出欢迎信息
        print("New connection", self.transport.getPeer())
        self.transport.write("Hello Server,I am the client\n")

    def sendMessage(self,msg):
        # 发送一条消息
        self.transport.write("MESSAGE:%s\n" % msg)

    def dataReceived(self,data):
        stdout.write(data)


    def connectionLost(self, reason):
        print("connection lost")


    def send_heartbeat(self):
        """
        发送心跳包
        """
        self.transport.write("心跳包...\n")
    
def gotProtocol(p):
    p.sendMessage("Hello server")
    # 添加两个延迟函数，分别在1秒之后，两秒之后运行。
    reactor.callLater(1,p.sendMessage,"This is send in a second")
    reactor.callLater(2,p.transport.loseConnection)


class WeChatClientFactory(ClientFactory):
    def __init__(self):
        self.p = WeChatClient()

    def startedConnecting(self, connector):
        print("Started to connect")

    def buildProtocol(self, addr):
        print("Connected.")
        return self.p

    def clientConnectionFailed(self, connector, reason):
        print("Lost connection. Reason:", reason)

    def clientConnectionLost(self, connector, reason):
        print("Connection failed. Reason:", reason)


if __name__ == '__main__':
    WeChatObj = WeChatClientFactory()

    task_send_heartbeat = task.LoopingCall(WeChatObj.p.send_heartbeat)
    task_send_heartbeat.start(2, now=False)


    reactor.connectTCP('localhost', 1234, WeChatObj)
    reactor.run()
    '''
    c = ClientCreator(reactor, WeChatClient)
    c.connectTCP('localhost', 1234).addCallback(gotProtocol)
    reactor.run()
    '''